package com.cyzy.controller;

import com.cyzy.dto.Result;
import com.cyzy.pojo.Student;
import com.cyzy.service.StudentService;
import com.cyzy.utils.CodeUtils;
import com.cyzy.utils.RedisUtil;
import com.cyzy.utils.SHA256Utils;
import com.cyzy.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentService studentService;
    @Autowired
    private CodeUtils codeUtils;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private TokenUtils tokenUtils;

    @PostMapping("/login")
    public Result login(@RequestBody Student student){
        System.out.println(student.getUuid());
        System.out.println(student.getUuid()+"------" +redisUtil.get(student.getUuid()));
        if(!redisUtil.get(student.getUuid()).equalsIgnoreCase(student.getCode())){  // 判断redis中的验证码是否正确
            return Result.error().message("验证码错误");
        }
        Student loginUser = studentService.login(student.getStudentPhone(),
                SHA256Utils.encryptPassword(student.getStudentPwd()));
        if(loginUser == null){
            return Result.error().message("账号或密码错误").code(401);  //判断账号密码的正误
        }
        String token = tokenUtils.generateToken(loginUser.getStudentId() + "");
        redisUtil.set(token, loginUser.getStudentId() + "");
        return Result.ok().data("login", loginUser).data("token", token);

    }

    @GetMapping("/getCode")
    public Result getCode(@RequestParam("uuid") String uuid){

        String base64 = codeUtils.getRandomCodeImage(); // 生成验证码
        System.out.println(codeUtils.getCode());

        redisUtil.set(uuid, codeUtils.getCode());  // 键： uuid   值：验证码
        redisUtil.setExpire(uuid, 60 * 5); // 设置redis   过期时间
        return Result.ok().data("base64", base64);
    }

    @GetMapping("/getById")
    public Result getById(@RequestParam("id") int id){
        Student byId = studentService.getById(id);
        return Result.ok().data("student", byId);
    }

    @PostMapping("/register")
    public Result addUser(@RequestBody Student student){
        return  studentService.insertUser(student);
    }


    @PostMapping("/getEmail")
    public Result getEmail(@RequestBody Student student){
        return studentService.getEmail(student);
    }


    @PostMapping("/emailLogin")
    public Result emilLogin(@RequestBody Student student){
        return studentService.emilLogin(student);
    }






}
